/**
 * @project sso-token-start V1.0
 * @Title:  TokenLoginHandler.java  
 * @Package com.gitee.kinbug.sso.handler 
 * Copyright(c) 2020 KinBug Co. Ltd. 
 * All right reserved. 
 */
package com.gitee.kinbug.sso.handler;

import javax.servlet.http.HttpServletRequest;

import com.gitee.kinbug.sso.model.AuthUser;
import com.gitee.kinbug.sso.store.SsoServiceStore;

/**   
 * Description:TODO(sso验证登录处理)   
 * @author: KinBug
 */
public class TokenLoginHandler {

    /**
     * client login
     *
     * @param sessionId sessionId
     * @param authUser authUser
     */
    public static void login(String sessionId, AuthUser authUser) {

        String storeKey = TokenIdHandler.parseStoreKey(sessionId);
        if (storeKey == null) {
            throw new RuntimeException("parseStoreKey Fail, sessionId:" + sessionId);
        }
        SsoServiceStore.put(storeKey, authUser);
    }

    /**
     * client logout
     *
     * @param sessionId sessionId
     */
    public static void logout(String sessionId) {

        String storeKey = TokenIdHandler.parseStoreKey(sessionId);
        if (storeKey == null) {
            return;
        }

        SsoServiceStore.remove(storeKey);
    }
    /**
     * client logout
     *
     * @param request HttpServletRequest
     */
    public static void logout(HttpServletRequest request) {
        String headerSessionId = request.getHeader(SsoServiceStore.ssoTokenProperties.getAuthKey());
        logout(headerSessionId);
    }


    /**
     * login check
     *
     * @param sessionId sessionId
     * @return AuthUser
     */
    public static AuthUser loginCheck(String sessionId){

        String storeKey = TokenIdHandler.parseStoreKey(sessionId);
        if (storeKey == null) {
            return null;
        }

        AuthUser ssoUser = SsoServiceStore.get(storeKey);
        if (ssoUser != null) {
            String version = TokenIdHandler.parseVersion(sessionId);
            if (ssoUser.getVersion().equals(version)) {
                if ((System.currentTimeMillis() - ssoUser.getExpireFreshTime()) > ssoUser.getExpireMinite()/2) {
                	ssoUser.setExpireFreshTime(System.currentTimeMillis());
                	SsoServiceStore.put(storeKey, ssoUser);
                }
                return ssoUser;
            }
        }
        return null;
    }


    /**
     * login check
     *
     * @param request HttpServletRequest
     * @return AuthUser AuthUser
     */
    public static AuthUser loginCheck(HttpServletRequest request){
        String headerSessionId = request.getHeader(SsoServiceStore.ssoTokenProperties.getAuthKey());
        return loginCheck(headerSessionId);
    }


}
